import { defineStore } from "pinia";
import { ref, computed } from "vue";
// 定义课程 store
export const useCourseStore = defineStore("course", () => {
    // 状态 - 课程列表 
    const courses = ref([
        { id: 1, name: "Web前端开发", teacher: "张老师", credit: 3 },
        { id: 2, name: "JavaScript 高级编程", teacher: "李老师", credit: 4 },
        { id: 3, name: "Vue 框架技术", teacher: "王老师", credit: 3 },
    ]);
    // 计算属性 - 总课程数
    const totalCourses = computed(() => courses.value.length);
    // 计算属性 - 总学分
    const totalCredits = computed(() => {
        return courses.value.reduce((sum, course) => sum + course.credit, 0);
    });
    // 添加课程
    const addcourse = (course) => {
        // 生成新 ID
        const newId =
            courses.value.length > 0
                ? Math.max(...courses.value.map((c) => c.id)) + 1
                : 1;
        courses.value.push({ ...course, id: newId });
    };
    // 删除课程
    const deleteCourse = (id) => {
        courses.value = courses.value.filter((course) => course.id !== id);
    };
    // 更新课程
    const updateCourse = (id, updatedcourse) => {
        const index = courses.value.findIndex((course) => course.id === id);
        if (index !== -1) {
            courses.value[index] = { ...updatedcourse, id };
        }

    };
    return {
        courses,
        totalCourses,
        totalCredits,
        addcourse,
        deleteCourse,
        updateCourse,
    };
});